﻿using System;
using BestHTTP.WebSocket;
using UnityEngine;
using LitJson;

namespace TlsService
{
    public class Tls
    {
        private TlsUri uri;
        private string endFlag;
        private WebSocket ws;
        public bool bOpen;
        public event Action<string> updateContent;

        public Tls()
        {
            uri = new TlsUri();
            TlsEndFlag flag = new TlsEndFlag();
            endFlag = JsonMapper.ToJson(flag);
        }

        public void Open()
        {
            var u = uri.Build();
            ws = new WebSocket(u);
            ws.OnOpen += OnOpen;
            ws.OnError += OnError;
            ws.OnMessage += OnMessage;
            ws.OnClosed += OnClose;
            ws.Open();
        }

        private async void OnOpen(WebSocket websocket)
        {
            bOpen = true;
        }

        public void SendAudioStream(byte[] buffer)
        {
            ws?.Send(buffer);
        }

        public void SendEndStream()
        {
            ws?.Send(endFlag);
            Close();
        }

        private void OnMessage(WebSocket websocket, string message)
        {
            Debug.Log(message);
            TlsMessage msg = JsonMapper.ToObject<TlsMessage>(message);
            if (msg.code == 0x00) 
            if (msg.final != 0x01)
            {
                TlsResult result = msg.result;
                if (result != null) 
                if (result.slice_type == 0x01)
                {
                     updateContent?.Invoke(result.voice_text_str);
                }
            }
        }

        private void OnError(WebSocket websocket, Exception ex)
        {
            Debug.Log(ex.Message);
        }

        private void OnClose(WebSocket websocket, ushort code, string message)
        {
            Debug.Log("close");
        }

        public void Close()
        {
            bOpen = false;
            ws?.Close();
        }
    }
}